package com.eca.emas.daemon;

import com.eca.emas.daemon.shared.EMASMailManager;
import com.eca.emas.daemon.shared.LocationChecker;

public class EMASDaemon {
	private static EMASDaemon instance = new EMASDaemon();
	private int updateInterval = 300;
	private Thread updateThread;
	private boolean daemonRunning = false;
	private long lastUpdateTime = 0;

	private EMASDaemon() {
		updateThread = new Thread(updateDatabaseRunnable);
	}

	public static EMASDaemon getInstance() {
		if (instance == null) {
			instance = new EMASDaemon();
		}
		return instance;
	}

	public void startDaemon() {
		if (!updateThread.isAlive()) {
			updateThread.start();
			daemonRunning = true;
		}
	}

	public void stopDeamon() {
		daemonRunning = false;
	}

	public void setUpdateInterval(int updateInterval) {
		this.updateInterval = updateInterval;
	}

	public int getUpdateInterval() {
		return this.updateInterval;
	}

	public boolean isDaemonRunning() {
		return daemonRunning;
	}

	private void verifyAllLocations() {
		LocationChecker checker = new LocationChecker();
		checker.checkAllLocations();
	}

	private Runnable updateDatabaseRunnable = new Runnable() {

		@Override
		public void run() {
			while (daemonRunning) {
				System.out.println("Data Updated...");
				long currentTime = System.currentTimeMillis();

				if (currentTime > (lastUpdateTime + 6 * updateInterval * 1000)) {
					WiregateManager.getInstance().updateServerList();
					EMASMailManager.getInstance().updateRecipients();
					verifyAllLocations();
					lastUpdateTime = currentTime;
				}

				WiregateManager.getInstance().updateAllServerData();

				try {
					Thread.sleep((long) updateInterval * 1000);
				} catch (InterruptedException e) {
					EMASMailManager.getInstance().sendExceptionToAllRecipients(
							e);
					e.printStackTrace();
				}
			}
		}
	};
}
